<?php

namespace App\Http\Resources\SiteLocation;

use App\Enums\OpenShop\InvestmentPromotion\SiteLocationEnum;
use App\Enums\OpenShop\InvestmentPromotion\UploadFileResourceEnum;
use App\Http\Resources\BaseResource;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationCustomerAnalysisModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationProductAnalysisModel;
use App\Remote\Rms\RmsUserRemote;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;

class AllClueSiteLocationDetailResource extends BaseResource
{
    /**
     * Transform the resource into an array.
     *
     * @param Request $request
     * @return array
     * @throws GuzzleException
     */
    public function toArray($request): array
    {

        return array_merge(
            [
                "siteType"         => $this->siteType,
                "siteTypeText"     => translateEnumCodeToCn(SiteLocationEnum::SITE_TYPE_TEXT, $this->siteType),
                "longitude"        => $this->longitude,
                "latitude"         => $this->latitude,
                "siteAddress"      => $this->siteAddress,
                "address"          => $this->address,
                "provinceCode"     => $this->provinceCode,
                "cityCode"         => $this->cityCode,
                "areaCode"         => $this->areaCode,
                "yearRent"         => bcdiv($this->clueRent, 1),
                "monthRent"        => bcdiv($this->clueRent, 12),
                "dayRent"          => bcdiv($this->clueRent, 365),
                "grade"            => OpenShopSiteLocationModel::HOUSE_GRADE_SIFT_MAPPING[$this->grade] ?? '',
                "shopGrade"        => OpenShopSiteLocationModel::HOUSE_SHOP_GRADE_SIFT_MAPPING[$this->shopGrade] ?? '',
                "isButton"         => true,   //todo

                "managerInfo" => $this->developConsultantId > 0 ?
                    (RmsUserRemote::getRmsUserByIds([$this->developConsultantId])[0] ?? new \stdClass()) : new \stdClass()
            ],
            [
                "advantageDisadvantage" => [
                    "siteAdvantage"   => $this->siteAdvantage,
                    "siteInferiority" => $this->siteInferiority
                ],
                "operateCondition"      => [
                    "currentFormat"       => $this->currentFormat,
                    "currentFormatText"   => translateEnumCodeToCn(SiteLocationEnum::CURRENT_FORMAT_TYPE_TEXT,
                        $this->currentFormat),
                    "operatingStatus"     => $this->operatingStatus,
                    "operatingStatusText" => translateEnumCodeToCn(SiteLocationEnum::OPERATING_STATUS_TYPE_TEXT,
                        $this->operatingStatus),
                    "leaseStatus"         => $this->leaseStatus,
                    "leaseStatusText"     => translateEnumCodeToCn(SiteLocationEnum::LEASE_STATUS_TEXT,
                        $this->leaseStatus),
                    "driveType"           => $this->driveType,
                    "driveTypeText"       => collect(SiteLocationEnum::DRIVE_TYPE_TEXT)->only(explode(",",
                        $this->driveType))->implode(","),
                ],
                "moveLineDesc"          => [
                    "flowLine"         => $this->flowLine,
                    "orientation"      => $this->orientation,
                    "visualLabel"      => $this->visualLabel,
                    "yinYangJie"       => $this->yinYangJie,
                    "yinYangJieText"   => translateEnumCodeToCn(SiteLocationEnum::YIN_YANG_JIE_TYPE_TEXT,
                        $this->yinYangJie),
                    "visualLabelText"  => translateEnumCodeToCn(SiteLocationEnum::VISUAL_LABEL_TEXT,
                        $this->visualLabel),
                    "flowLineText"     => translateEnumCodeToCn(SiteLocationEnum::FLOW_LINE_TYPE_TEXT,
                        $this->flowLine),
                    "orientationText"  => translateEnumCodeToCn(SiteLocationEnum::ORIENTATION_TYPE_TEXT,
                        $this->orientation),
                    "streetLength"     => $this->streetLength,
                    "streetLengthText" => translateEnumCodeToCn(SiteLocationEnum::STREET_LENGTH_TEXT,
                        $this->streetLength),
                ],
                "engineeringConditions" => [
                    "decorationShopType"      => $this->decorationShopType,
                    "decorationShopTypeText"  => translateEnumCodeToCn(SiteLocationEnum::DECORATION_SHOP_TEXT,
                        $this->decorationShopType),
                    "doorWidth"               => $this->doorWidth,
                    "floorHeight"             => $this->floorHeight,
                    "area"                    => $this->area,
                    "electricityConsumption"  => $this->electricityConsumption,
                    "exhaustAirVolume"        => $this->exhaustAirVolume,
                    "airConditionerCType"     => $this->airConditionerCType,
                    "airConditionerCTypeText" => translateEnumCodeToCn(SiteLocationEnum::AIR_CONDITIONER_TYPE_TEXT,
                        $this->airConditionerCType),
                    "upperWaterDiameter"      => $this->upperWaterDiameter,
                    "lowerWaterDiameter"      => $this->lowerWaterDiameter,
                    "isReformWater"           => $this->isReformWater,
                    "isReformWaterText"       => translateEnumCodeToCn(SiteLocationEnum::IS_REFORM_WATER_TEXT,
                        $this->isReformWater),
                ],
                "businessConditions"    => [
                    "rentType"             => $this->rentType,
                    "rentTypeText"         => translateEnumCodeToCn(SiteLocationEnum::RENT_TYPE_TEXT,
                        $this->rentType),
                    "fixedRent"            => $this->fixedRent,
                    "remind"               => $this->remind,
                    "rentPaymentCycle"     => $this->rentPaymentCycle,
                    "rentPaymentCycleText" => translateEnumCodeToCn(SiteLocationEnum::RENT_PAYMENT_TEXT,
                        $this->rentPaymentCycle),
                    "deposit"              => $this->deposit,
                    "leaseTerm"            => $this->leaseTerm,
                    "rentFreePeriod"       => $this->rentFreePeriod,
                    "restrictedSales"      => $this->restrictedSales,
                    "restrictedSalesText"  => collect(SiteLocationEnum::RESTRICTED_SALES_TEXT)->only(explode(",",
                        $this->restrictedSales))->implode(","),
                ]
            ],
            $this->getAttachFileInfo(UploadFileResourceEnum::SITE_LOCATION_DATABASE_LIST),
            [
                "customerAnalysisFile" => $this->getCustomerAttachFileInfo(
                    UploadFileResourceEnum::CUSTOMER_ANALYSIS_DATABASE_LIST,
                    (function (Collection $collectionMap = null) {
                        $collection = new Collection();
                        if ($collectionMap) {
                            $collectionMap->each(function ($currentCollection) use (&$collection) {
                                if ($currentCollection->fileRel) {
                                    $collection = $collection->merge($currentCollection->fileRel);
                                }
                            });
                        }
                        return $collection;
                    })($this->customerAnalysisRel)
                )
            ],
            [
                "competingProductsAnalysisFile" => $this->getCustomerAttachFileInfo(
                    UploadFileResourceEnum::PRODUCT_ANALYSIS_DATABASE_LIST,
                    (function (Collection $collectionMap = null) {
                        $collection = new Collection();
                        if ($collectionMap) {
                            $collectionMap->each(function ($currentCollection) use (&$collection) {
                                if ($currentCollection->fileRel) {
                                    $collection = $collection->merge($currentCollection->fileRel);
                                }
                            });
                        }
                        return $collection;
                    })($this->competingProductsAnalysisRel)
                )
            ],
            [
                "complementProductsAnalysisFile" => $this->getCustomerAttachFileInfo(
                    UploadFileResourceEnum::PRODUCT_ANALYSIS_DATABASE_LIST,
                    (function (Collection $collectionMap = null) {
                        $collection = new Collection();
                        if ($collectionMap) {
                            $collectionMap->each(function ($currentCollection) use (&$collection) {
                                if ($currentCollection->fileRel) {
                                    $collection = $collection->merge($currentCollection->fileRel);
                                }
                            });
                        }
                        return $collection;
                    })($this->complementProductsAnalysisRel)
                )
            ],
            [
                "customerAnalysis"                   => SiteLocationCustomerAnalysisResource::collection($this->handleCustomerAnalysis())->resource->toArray(),
                "complementProductsAnalysis"         => SiteLocationProductAnalysisResource::collection(
                    $this->productAnalysisRel ? $this->productAnalysisRel->where("type",
                        OpenShopSiteLocationProductAnalysisModel::TYPE_1) : []
                )->resource->toArray(),
                "mutuallyComplementProductsAnalysis" => SiteLocationProductAnalysisResource::collection(
                    $this->productAnalysisRel ? $this->productAnalysisRel->where("type",
                        OpenShopSiteLocationProductAnalysisModel::TYPE_2) : []
                )->resource->toArray(),
            ]
        );
    }

    /**
     * @return Collection
     */
    public function handleCustomerAnalysis(): Collection
    {
        if ($this->customerAnalysisRel) {
            return $this->customerAnalysisRel->filter(function ($v) {
                foreach (OpenShopSiteLocationCustomerAnalysisModel::$filterFields as $field) {
                    if (!empty($v->{$field})) {
                        return true;
                    }
                }
                return false;
            })->values();
        }
        return new Collection();
    }

    public function getCustomerAttachFileInfo(array $attachMap, Collection $collection = null): array
    {
        return collect($attachMap)->map(function ($v, $k) use($collection) {
            return [
                "key" => $v,
                "url" => $collection ? $collection->where("position", $k)->map(function ($v) {
                    if ($v->isPublic == 1) {
                        $v->url = picturePath($v->url);
                    } else {
                        $v->url = privateFilePath($v->url);
                    }
                    return $v;
                })->pluck("url")->values()->toArray() : []
            ];
        })->values()->pluck("url", "key")->toArray();
    }
}
